package cn.newgrand.netcall.offlinefiletransfer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JPanel;

import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.ui.ChatRoomClosingListener;
import org.jivesoftware.spark.ui.ChatRoomNotFoundException;

import cn.newgrand.netcall.offlinefiletransfer.ui.ReceiveMessage;

public class InnerPanelManager {
	
	private static InnerPanelManager instance;
	private Map<String,Map<String,List<JPanel>>> map = new HashMap<String,Map<String,List<JPanel>>>();
	
	public static InnerPanelManager getInstance(){
		
		if(instance==null){
			instance = new InnerPanelManager();
		}
		return instance;
	}
	
	public void putPanel(final String roomJID,String fileName,JPanel panel) throws ChatRoomNotFoundException{
		Map<String,List<JPanel>> temp =null;
		List<JPanel> temp2 = null;
		if(map.get(roomJID)==null){
			temp = new HashMap<String, List<JPanel>>();
			SparkManager.getChatManager().getChatContainer().getChatRoom(roomJID).addClosingListener(new ChatRoomClosingListener() {
				
				@Override
				public void closing() {
					// TODO Auto-generated method stub
					if(map.get(roomJID)!=null)
						map.remove(roomJID);
				}
			});
			map.put(roomJID, temp);
		}
		temp =  map.get(roomJID);
		if(temp.get(fileName)==null){
			temp2 =new ArrayList<JPanel>();
			temp.put(fileName, temp2);
		}
		if(!temp.get(fileName).contains(panel))
			temp.get(fileName).add(panel);
	}
	
	public List<JPanel> getPanel(String roomJID,String fileName){
		Map<String,List<JPanel>> temp =null;
		if(map.get(roomJID)!=null){
			temp =  map.get(roomJID);
			if(temp.get(fileName)!=null){
				return temp.get(fileName);
			}
		}
		return null;
	}
	
	public void cancelTransfer(String roomJID,String fileName){
		List<JPanel> ps = getPanel(roomJID,fileName);
		if(ps!=null){
			for(JPanel p:ps){
				ReceiveMessage m = (ReceiveMessage) p;
				m.requestRejected();
			}
		}
	}
}
